<?php
/**
 * 个人空间
 */
class SpaceAction extends Action{
   public $user_info;
	function _initialize() {
		if (!is_numeric($_GET['uid']) && is_string($_GET['uid'])) {
			$domainuser = D('User')->getUserByIdentifier(h($_GET['uid']), 'domain');
	   		if ($domainuser) {
	   			$this->uid = $domainuser['uid'];
	   			$this->assign('uid',$this->uid);
	   		}else {
   	   			$this->error('用户不存在');
	   		}
		}

		if ('detail' != ACTION_NAME) {
			$this->user_info = D('User')->getUserByIdentifier($this->uid);
	   	   	if ($this->user_info) {
				$this->assign('userinfo',$user_info);
	   	   	} else {
   	   			$this->error('用户不存在');
	   		}
	
	       	$this->__getSpaceCount( $this->uid );
		}
	}

	private function __getSpaceCount($uid) {
		$followInfo = getUserFollow($uid);
		$data['followstate'] = D('Follow','weibo')->getState($this->mid, $uid, 0);
		//$data['isBlackList'] = isBlackList($this->mid,$uid);
		//$data['privacy']     = D('UserPrivacy','home')->getPrivacy($this->mid,$uid);
		$data['spaceCount']['miniblog']   = model('UserCount')->getUserWeiboCount($uid);
		$data['spaceCount']['following']  = $followInfo['following'];
		$data['spaceCount']['follower']   = $followInfo['follower'];
		$data['spaceCount']['message']   = 0;
		//$data['hotTopic'] = D('Topic','weibo')->getHot();
		//$data['usertags'] = D('UserTag')->getUserTagList( $this->uid );
        //$data['verified'] = M('user_verified')->field('verified,info')->where("uid={$this->uid}")->find();
		$this->assign( $data );
	}

    // 用户空间首页
    public function index()
    {
		$map="status =1 AND uid={$this->uid}";
	    $db_prefix  =  C('DB_PREFIX');
		
	    if($_GET['k'] || $_POST['k']){
	      $search_key   =  $this->__getSearchKey ();
	      $keyinfo = M('tag')->where("tag_name='{$search_key}'")->find();
		  
	     if ($keyinfo) {
		 $list = M('weibo_tag')->where("tag_id=".$keyinfo['tag_id'])->field('weibo_id')->findAll();
			
		 $weibo_ids = getSubByKey($list, 'weibo_id');
	     $map.=" AND weibo_id in (".implode(',',$weibo_ids).")";
	     }
	    }
	 $weibo  = M('weibo');	
	 $count = $weibo->where($map)->count(); 
	 $p = new Page ( $count, 10 );
	 
	 $weibolist = $weibo->where($map)->limit($p->firstRow.','.$p->listRows)->order('utime DESC')->findAll ();
	 foreach ($weibolist as $k => $v) {
	   if($weibolist[$k]['tag']){
	    $weibolist[$k]['tag']=explode(',',$weibolist[$k]['tag']);
	   }
     }
     $page = $p->show ();
	 $this->assign ( "page", $page );	 
	 
	 $this->assign('bloglist',$weibolist);
	 
     $this->setTitle($this->user_info['uname'] . '的空间');
     $this->display();
    }
    public function blog(){
	 $db_prefix  =  C('DB_PREFIX');
	 $weibo_id = empty($_GET['id'])? 0 : intval($_GET['id']);
	 $blog = M('')->field('b.*, w.*')->table("{$db_prefix}blog AS b RIGHT JOIN {$db_prefix}weibo AS w ON b.blog_id=w.blog_id")->where('w.weibo_id='.$weibo_id)->find();
	 if(empty($blog)){
	   $this->error('您查看的页面不存在，或者已经删除');
	 }
	 $blog['tag']=$this->_gettag($blog['weibo_id']);
	 $this->assign('blog',$blog);
	 $this->setTitle($blog['title']?$blog['title']:$blog['tag'][0]['tag_name'] . '-'.$this->user_info['uname'] . '的空间');
	 $this->display();
	}
    //个人资料
    function profile(){
    	$pUserProfile = D('UserProfile');
    	$pUserProfile->uid = $this->uid;
    	$data['userInfo']  = $pUserProfile->getUserInfo();
    	$this->assign( $data );
    	$this->setTitle(getUserName($this->uid) . '的详细资料');
    	$this->display();
    }

    // 查看微博详细
    function detail(){
    	$intId = intval( $_GET['id'] );
	    $data['mini']      =  D('Operate','weibo')->getOneLocation( $intId );
	    if(!$data['mini']) $this->error('提交错误参数');
		$data['comment']   =  D('Comment','weibo')->getComment( $intId );
		$data['privacy'] = D('UserPrivacy','home')->getPrivacy($this->mid,$data['mini']['uid']);
    	$this->assign( $data );
	    $this->uid = $data['mini']['uid'];

		$user_info = D('User')->getUserByIdentifier($this->uid);
	   	if ($user_info) {
			$this->assign('userinfo',$user_info);
	   	}
	    $this->__getSpaceCount( $this->uid );

	    $this->setTitle(getUserName($this->uid) . '的微博');
    	$this->display();
    }

    //关注
    function follow(){
    	$data['type'] = ($_GET['type']=='follower')?'follower':'following';
    	if($data['type'] == 'following'){
    		//关注分组列表
	    	$data['gid']  = is_numeric($_GET['gid'])?$_GET['gid']:'all';
	    	$group_list = D('FollowGroup','weibo')->getGroupList($this->uid);
	    	//调整分组列表
	    	if(!empty($group_list)){
		    	$group_count = count($group_list);
		    	for($i=0;$i<$group_count;$i++){
		    		if($group_list[$i]['follow_group_id'] != $data['gid']){
		    			$group_list[$i]['title'] = (strlen($group_list[$i]['title'])+mb_strlen($group_list[$i]['title'],'UTF8'))/2>8?getShort($group_list[$i]['title'],3).'...':$group_list[$i]['title'];
		    		}
		    		if($i<2){
		    			$data['group_list_1'][] = $group_list[$i];
		    		}else{
		    			if($group_list[$i]['follow_group_id'] == $data['gid']){
		    				$data['group_list_1'][2]  = $group_list[$i];
		    				continue;
		    			}
		    			$data['group_list_2'][] = $group_list[$i];
		    		}
		    	}
		    	if(empty($data['group_list_1'][2]) && !empty($data['group_list_2'][0])){
		    		$data['group_list_1'][2] = $data['group_list_2'][0];
		    		unset($data['group_list_2'][0]);
		    	}
	    	}
    	}
    	// 关注的人列表
    	$data['list'] = D('Follow','weibo')->getList($this->uid,$data['type'],0,$data['gid']);

    	$this->assign($data);
    	$this->setTitle(getUserName($this->uid) . '的' . ($data['type'] == 'follower' ? '粉丝' : '关注'));
    	$this->display();
    }
	
	/*得到 文章的前 N个标签
	* $blog_id    博客id
	* $limit      获取标签个数
	*/
	private function _gettag($weibo_id,$limit='') {
	   $db_prefix  =  C('DB_PREFIX');
	   $tag=M('');
	   $tag_names = $tag->field('t.tag_name')->table("{$db_prefix}weibo_tag AS wt LEFT JOIN {$db_prefix}tag AS t ON wt.tag_id=t.tag_id")
	         ->where('weibo_id='.$weibo_id)->limit($limit)->order('wt.tag_id ASC')->findAll();
			 //echo $tag->getLastSql();
	   return $tag_names;
	}
	private function __getSearchKey() {
		$key = '';
		// 为使搜索条件在分页时也有效，将搜索条件记录到SESSION中
		if (isset ( $_REQUEST ['k'] ) && ! empty ( $_REQUEST ['k'] )) {
			if ($_GET ['k']) {
				$key = html_entity_decode ( urldecode ( $_GET ['k'] ), ENT_QUOTES );
			} elseif ($_POST ['k']) {
				$key = $_POST ['k'];
			}
			// 关键字不能超过30个字符
			if (mb_strlen ( $key, 'UTF8' ) > 30)
				$key = mb_substr ( $key, 0, 30, 'UTF8' );
			$_SESSION ['home_user_search_key'] = serialize ( $key );
		
		} else if (is_numeric ( $_GET [C ( 'VAR_PAGE' )] )) {
			$key = unserialize ( $_SESSION ['home_user_search_key'] );
		
		} else {
			//unset($_SESSION['home_user_search_key']);
		}
		//echo unserialize ($_SESSION ['home_user_search_key']);
		return trim ( $key );
	}
}